package com.cnswhy.cloud.server.core.service.shop.impl;


import cn.hutool.core.collection.CollUtil;
import com.cnswhy.cloud.common.core.base.service.SuperServiceImpl;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dao.ShopProductMapper;
import com.cnswhy.cloud.server.core.dto.*;
import com.cnswhy.cloud.server.core.entity.ShopProduct;
import com.cnswhy.cloud.server.core.entity.ShopProductGallery;
import com.cnswhy.cloud.server.core.entity.ShopProductStock;
import com.cnswhy.cloud.server.core.service.ShopProductGalleryService;
import com.cnswhy.cloud.server.core.service.merchant.MerchantService;
import com.cnswhy.cloud.server.core.service.shop.ShopProductService;
import com.cnswhy.cloud.server.core.vo.PagerVo;
import com.cnswhy.cloud.server.core.vo.shop.ProductAppPageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//import com.cnswhy.cloud.common.redis.service.RedisService;

/**
 * <p>
 * 业务实现类
 * 商品详情表
 * </p>
 *
 * @author cnswhy
 * @date 2020-09-30
 */
@Slf4j
@Service

public class ShopProductServiceImpl extends SuperServiceImpl<ShopProductMapper, ShopProduct> implements ShopProductService {
    @Autowired
    RedisService redisService;
    @Autowired
    MerchantService merchantService;
    @Autowired
    ShopProductGalleryService shopProductGalleryService;
    @Override
    public ShopProductSku queryShopProductSku(Long stockId)
    {
        return getBaseMapper().queryShopProductSku(stockId);
    }

    @Override
    public PagerVo<ProductAppPageVo> queryProductAppPage(ProductQueryBo bo) {
        int totalPageData = getBaseMapper().totalAppPage(bo);
        PagerVo<ProductAppPageVo> pager = new PagerVo<ProductAppPageVo>(bo.getCurrentPage(), bo.getPageSize(),
                totalPageData);
        bo.setStart(pager.getStart());
        bo.setEnd(pager.getEnd());
        List<ProductAppPageVo> listPageData = getBaseMapper().queryAppPage(bo);
        String pfx = String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX));
        for(ProductAppPageVo productAppPageVo : listPageData){
            if(StringUtils.isNotBlank(productAppPageVo.getUrl())){
                productAppPageVo.setThumbnailImg(productAppPageVo.getUrl());
            }else{
                productAppPageVo.setThumbnailImg(pfx + productAppPageVo.getThumbnailImg());
            }
        }
        pager.setData(listPageData);
        return pager;
    }

    @Override
    public ProductAppDetailVo queryProductAppById(Long id)
    {
        ProductAppDetailVo vo = getBaseMapper().queryProductAppById(id);
        /*if (CollUtil.isNotEmpty(vo.getSpecList())) {
            for (ShopSpecVo specVo : vo.getSpecList()){
                vo.getSpecList().remove(specVo);
                for(SpecValueEntity specValueEntity: specVo.getSpecValueList()){
                    specVo.getSpecValueList().remove(specValueEntity);
                    specValueEntity.setType(0);
                    specValueEntity.setProductId(0L);
                    specValueEntity.setSortOrder(0);
                    specValueEntity.setSpecId(0L);
                    specVo.getSpecValueList().add(specValueEntity);
                }
                vo.getSpecList().add(specVo);
            }
        }*/
        // 设置图片访问前缀
        if(StringUtils.isBlank(vo.getUrl())){
            String pfx = String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX));
            vo.setThumbnailImg(pfx + vo.getThumbnailImg());
            vo.setPosterImg(pfx + vo.getPosterImg());
        }else{
            vo.setThumbnailImg(vo.getUrl());
            vo.setPosterImg(vo.getPosterUrl());
            List<ShopProductGallery> shopProductGalleryList = shopProductGalleryService.list(Wraps.<ShopProductGallery>lbQ().eq(ShopProductGallery::getProductId,vo.getId()));
            String sliderImgs = null;
            for(ShopProductGallery shopProductGallery : shopProductGalleryList){
                if(StringUtils.isBlank(sliderImgs)){
                   sliderImgs = shopProductGallery.getOriginal();
                }else {
                    sliderImgs = sliderImgs + "," + shopProductGallery.getOriginal();
                }
            }
            vo.setSliderImgs(sliderImgs);
            vo.setUrlPrefix("");
        }

        // 设置规格图片
        this.getSpecImg(vo);

        //vo.setMerchant(merchantService.getById(vo.getMerchantId()));
        //vo.setMerchant(merchantService.getMerchantDetail(vo.getMerchantId()));


        return vo;
    }



    /**
     * 描述：设置规格图片
     * 作者：张润泽
     * 时间：2019年9月2日 上午11:43:27
     * @param vo
     */
    private void getSpecImg(ProductAppDetailVo vo)
    {
        // 计算规格笛卡尔积
        String pfx = String.valueOf(redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.FTP_PATH_PREFIX));
        List<List<SpecValueEntity>> specArr = new ArrayList<List<SpecValueEntity>>();
        if (CollUtil.isNotEmpty(vo.getSpecList()))
        {
            List<String> result = new ArrayList<String>();
            for (ShopSpecVo specVo : vo.getSpecList())
            {
                specArr.add(specVo.getSpecValueList());
            }
            this.cartesianProduct(specArr, result, 0, "");

            for (ShopSpecVo specVo : vo.getSpecList())
            {
                // 获取需要图片的规格值列表
                if (specVo.getHasImg() != null && specVo.getHasImg().equals(1))
                {
                    for (SpecValueEntity value : specVo.getSpecValueList())
                    {
                        for (String ids : result)
                        {
                            // 匹配规格图片
                            if (ids.contains(value.getId() + ","))
                            {
                                for (ShopProductStock stock : vo.getStockList())
                                {
                                    // 设置规格图片
                                    if ((ids.substring(0, ids.length() - 1)).equals(stock.getSpecIds()))
                                    {
                                        //value.setImgUrl(stock.getImgUrl());
                                        if(StringUtils.isNotBlank(stock.getUrl())){
                                            value.setImgUrl(stock.getUrl());
                                        }else{
                                            value.setImgUrl(pfx + stock.getImgUrl());
                                        }

                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }
    }

    /**
     * 描述：计算笛卡尔积
     * 作者：张润泽
     * 时间：2019年9月2日 上午11:43:01
     * @param dimvalue
     * @param result
     * @param layer
     * @param curstring
     */
    private void cartesianProduct(List<List<SpecValueEntity>> dimvalue, List<String> result, int layer,
                                  String curstring)
    {
        //大于一个集合时：
        if (layer < dimvalue.size() - 1)
        {
            //大于一个集合时，第一个集合为空
            if (dimvalue.get(layer).size() == 0)
                cartesianProduct(dimvalue, result, layer + 1, curstring);
            else
            {
                for (int i = 0; i < dimvalue.get(layer).size(); i++)
                {
                    StringBuilder s1 = new StringBuilder();
                    s1.append(curstring);
                    s1.append(dimvalue.get(layer).get(i).getId());
                    s1.append(",");
                    cartesianProduct(dimvalue, result, layer + 1, s1.toString());
                }
            }
        }
        //只有一个集合时：
        else if (layer == dimvalue.size() - 1)
        {
            //只有一个集合，且集合中没有元素
            if (dimvalue.get(layer).size() == 0)
                result.add(curstring);
                //只有一个集合，且集合中有元素时：其笛卡尔积就是这个集合元素本身
            else
            {
                for (int i = 0; i < dimvalue.get(layer).size(); i++)
                {
                    result.add(curstring + dimvalue.get(layer).get(i).getId() + ",");
                }
            }
        }
    }

}
